<template>
	<el-dialog
		:title="'复修开卡'"
		v-model="visible"
		:width="1048"
		destroy-on-close
		@closed="$emit('closed')"
	>
		<el-tabs>
			<el-tab-pane label="复修信息">
				<el-descriptions
					:column="4"
					border
					label-align="right"
					title="排缸信息"
				>
					<el-descriptions-item min-width="80">
						<template #label>单号</template>
						{{ potdata.code }}
					</el-descriptions-item>
					<el-descriptions-item min-width="80">
						<template #label>缸号</template>
						{{ potdata.dyelot }}
					</el-descriptions-item>
					<el-descriptions-item min-width="80">
						<template #label>颜色</template>
						{{ potdata.color.name }}
					</el-descriptions-item>
					<el-descriptions-item min-width="80">
						<template #label>批号</template>
						{{ potdata.lot_name }}
					</el-descriptions-item>
					<el-descriptions-item min-width="80">
						<template #label>进缸</template>
						{{ potdata.lot_name }}
					</el-descriptions-item>
					<el-descriptions-item min-width="80">
						<template #label>出缸</template>
						{{ potdata.lot_name }}
					</el-descriptions-item>
					<el-descriptions-item min-width="80">
						<template #label>对样</template>
						{{ potdata.lot_name }}
					</el-descriptions-item>
					<el-descriptions-item min-width="80">
						<template #label>辅料成本</template>
						{{ potdata.lot_name }}
					</el-descriptions-item>
				</el-descriptions>
				<el-form
					:model="potdata"
					:rules="potdatarules"
					ref="dialogPotdata"
					label-width="70px"
					label-position="right"
					class="el-tabs--border-card"
					style="border: 1px solid #dedfe0"
				>
					<el-row>
						<el-col :span="8">
							<el-form-item
								label="损失原因"
								prop="repairreason.name"
							>
								<skAutoComplete
									v-model="potdata.repairreason.name"
									:name="'repairreason'"
									:placeholder="'请选择损失原因'"
									@select="repairreasonSelect"
								>
								</skAutoComplete>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item
								label="复修原因"
								prop="repairreason_id"
							>
								<skDicSelect
									v-model="potdata.repairreason_id"
									:placeholder="'请选择复修原因'"
									:data="repairreason.details"
								>
								</skDicSelect>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item label="复修开卡">
								<el-checkbox-group v-model="repairpot">
									<el-checkbox label="重新开卡" />
									<el-checkbox label="生成计划" />
								</el-checkbox-group>
							</el-form-item>
						</el-col>
						<el-col :span="24">
							<el-form-item label="备注" prop="remark">
								<el-input v-model="potdata.remark" />
							</el-form-item>
						</el-col>
					</el-row>
					<sc-VxeTable
						ref="xGrid1"
						:data="potdata.details"
						:gridOps="{ height: 259 }"
						:tablecode="'pro_pot_repair'"
					>
					</sc-VxeTable>
				</el-form>
			</el-tab-pane>
			<el-tab-pane label="重新开卡" v-if="repairpot.includes('重新开卡')">
				<el-form
					:model="form"
					:rules="rules"
					ref="dialogForm"
					label-width="70px"
					label-position="right"
					class="el-tabs--border-card"
					style="border: 1px solid #dedfe0"
				>
					<el-row>
						<el-col
							:span="13"
							style="border-right: 1px solid #dedfe0"
						>
							<sc-VxeTable
								:tablecode="'pro_pot_rev_list'"
								:data="form.raw"
								:gridOps="gridOps"
								:gridEvts="gridEvent"
								ref="subbe"
								:sortable="true"
							>
							</sc-VxeTable>
						</el-col>
						<el-col :span="11">
							<el-row>
								<el-col :span="8">
									<el-form-item
										label="订单数"
										prop="quantity"
									>
										<el-input-number
											v-model="form.quantity"
											:step="25"
											:min="5"
										/>
									</el-form-item>
								</el-col>
								<el-col :span="8">
									<el-form-item
										label="投料比"
										prop="feeding_ratio"
									>
										<el-input
											v-model="form.feeding_ratio"
											disabled
										/>
									</el-form-item>
								</el-col>
								<el-col :span="8">
									<el-form-item
										label="投料"
										prop="yarn_quantity"
									>
										<el-input
											v-model="form.yarn_quantity"
											disabled
										/>
									</el-form-item>
								</el-col>
								<el-col :span="8">
									<el-form-item label="色号" prop="color_id">
										<el-input v-model="form.color.code" />
									</el-form-item>
								</el-col>
								<el-col :span="8">
									<el-form-item label="色名">
										<el-input
											v-model="form.color.name"
											disabled
										/>
									</el-form-item>
								</el-col>
								<el-col :span="8">
									<el-form-item
										label="脱水时长"
										prop="tstime"
									>
										<skDicSelect
											v-model="form.tstime"
											:code="'TsTime'"
											:placeholder="'请选择脱水时长'"
										>
										</skDicSelect>
									</el-form-item>
								</el-col>

								<el-col :span="12">
									<el-form-item label="染缸" prop="loom_id">
										<skAutoComplete
											v-model="form.loom.name"
											:name="'loom'"
											@select="loomSelect"
											:params="getQuantity"
											:sort="'dosage'"
										>
										</skAutoComplete>
									</el-form-item>
								</el-col>
								<el-col :span="12">
									<el-form-item label="浴比" prop="ratio">
										<el-input v-model="form.ratio" />
									</el-form-item>
								</el-col>
								<el-col :span="12">
									<el-form-item label="浴量">
										<el-input
											v-model="form.bath_qty"
											disabled
										/>
									</el-form-item>
								</el-col>

								<el-col :span="12">
									<el-form-item
										label="配方"
										prop="revision_id"
									>
										<el-button-group>
											<el-button
												type="primary"
												icon="ElIconSearch"
												@click="openBomPot"
												auto-insert-space
												>选大货</el-button
											>
											<el-button
												type="danger"
												icon="ElIconSearch"
												@click="openBomColor"
												auto-insert-space
												>选小样</el-button
											>
										</el-button-group>
									</el-form-item>
								</el-col>
								<el-col :span="24">
									<el-form-item label="工艺" prop="rscode">
										<skAutoChoose
											v-model="form.dyecraft.name"
											:name="'dyecraft'"
											@select="
												(data) => (form.dyecraft = data)
											"
											:asKey="'rscode'"
											:asField="'code'"
											:assign="form"
											:prepend_width="'60px'"
											:params="getRsParams"
										>
											<template #prepend>{{
												form.dyecraft.code
											}}</template>
										</skAutoChoose>
									</el-form-item>
								</el-col>
								<el-col :span="24">
									<el-form-item label="工艺">
										<el-input
											v-model="form.dyecraft.data"
											type="textarea"
											disabled
											:rows="5"
										></el-input>
									</el-form-item>
								</el-col>
								<el-col :span="24">
									<el-form-item
										label="后处理"
										prop="rscodeend"
									>
										<skAutoChoose
											v-model="form.dyeendcraft.name"
											:name="'dyeendcraft'"
											@select="
												(data) =>
													(form.dyeendcraft = data)
											"
											:asKey="'rscodeend'"
											:asField="'code'"
											:params="getRsEndParams"
											:assign="form"
											:prepend_width="'60px'"
										>
											<template #prepend>{{
												form.dyeendcraft.code
											}}</template>
										</skAutoChoose>
									</el-form-item>
								</el-col>
								<el-col :span="24">
									<el-form-item
										label="生产要求"
										prop="dgremark"
									>
										<el-input v-model="form.dgremark" />
									</el-form-item>
								</el-col>
							</el-row>
						</el-col>
					</el-row>
				</el-form>
			</el-tab-pane>
		</el-tabs>

		<template #footer>
			<el-button @click="visible = false">取 消</el-button>
			<el-button type="primary" :loading="isSaveing" @click="submit()"
				>保 存</el-button
			>
		</template>
	</el-dialog>

	<colorbrowser
		v-model="dialog.color"
		@close="dialog.color = false"
		@select="selectColor"
		:params="{ main_id: form.color_id }"
	>
	</colorbrowser>
	<potbrowser
		v-model="dialog.pot"
		@close="dialog.pot = false"
		@select="selectPotColor"
		:params="{ color_id: form.color_id }"
	>
	</potbrowser>
</template>

<script>
import tool from "@/utils/tool";
import skDicSelect from "@/components/skDicSelect";
import skAutoChoose from "@/components/skAutoChoose";
import skAutoComplete from "@/components/skAutoComplete";
import skBrowserChoose from "@/components/skBrowserChoose";
import colorbrowser from "@/views/pro/color/browser";
import potbrowser from "@/views/pro/pot/browser";
import XEUtils from "xe-utils";

export default {
	emits: ["success", "closed"],
	components: {
		skAutoChoose,
		skDicSelect,
		skAutoComplete,
		skBrowserChoose,
		colorbrowser,
		potbrowser,
	},
	data() {
		return {
			mode: "add",
			repairreason: { name: "", details: [] },
			repairpot: [],
			dialog: {
				pot: false,
				color: false,
			},
			gridOps: {
				columns: [
					{
						field: "material.name",
						event: {
							select: ({ e, row }) => {
								row["material"] = e;
								row["procedure"] = e.procedure;
								row["uunit"] = e.uunit ?? {};
								row["ounit"] = e.ounit ?? {};
								row["uunit_id"] = e.uunit_id;
								row["ounit_id"] = e.ounit_id;
								this.calcAuxiliaryQuantity(row);
								this.calcAuxiliaryAmount(row);
							},
						},
					},
					{
						field: "rate",
						event: {
							keyup: ({ row }) => {
								this.calcAuxiliaryQuantity(row);
								this.calcAuxiliaryAmount(row);
							},
						},
					},
					{
						field: "quantity",
						event: {
							keyup: ({ row }) => {
								this.calcAuxiliaryRate(row);
								this.calcAuxiliaryAmount(row);
							},
						},
					},
				],
			},
			gridEvent: {},
			titleMap: "",

			form: {
				place: {},
				color: { name: "" },
				loom: { name: "" },
				dyeendcraft: {},
				raw: [],
				dyecraft: [],
				revision_id: "",

				remark: "",
			},
			potdata: {
				place: {},
				color: { name: "" },
				repairreason: {},
				repairreason_id: null,
			},
			potdatarules: {
				remark: { required: true, message: "复修的备注必填" },
				repairreason_id: { required: true, message: "复修的原因必填" },
				"repairreason.name": {
					required: true,
					message: "复修的损失原因必填",
				},
			},

			rules: {
				// 'main.ColorShade_id': { required: true, message: "请选择颜色深浅" },
				tstime: { required: true, message: "脱水时长必选" },
				loom_id: { required: true, message: "必须选择染缸" },
				ratio: { required: true, message: "浴比必填" },
				rscode: { required: true, message: "必须选择工艺" },
				revision_id: { required: true, message: "必须选择配方" },
				color_id: { required: true, message: "复修的颜色必填" },
				quantity: { required: true, message: "开卡订单数必填" },
			},
			visible: false,
			isSaveing: false,
		};
	},
	mounted() {},
	watch: {
		"form.ratio"(val) {
			this.form.bath_qty = val * this.form.dosage;
			this.resetComputAuxiliary();
		},
		"form.quantity"(val) {
			this.form.feeding_ratio = (
				(this.form.yarn_quantity / val) *
				1000
			).toFixed(0);
		},
	},
	methods: {
		repairreasonSelect(data) {
			this.repairreason = data.name ? data : { name: "", details: [] };
		},
		getRsEndParams() {
			return {
				category_id: 2,
				materialid: this.form.material_id,
				parent_code: this.form.rscode,
			};
		},
		getRsParams() {
			let material_id = this.form.material_id;
			let loom_id = this.form.loom_id;
			let rawids = [];
			this.form.raw?.filter((raw) => {
				let spec = raw.material.spec.substr(0, 1);
				if (
					["1", "2", "3", "4"].indexOf(spec) > -1 &&
					rawids.indexOf(spec) == -1
				)
					rawids.push(spec);
			});
			return {
				materialid: material_id,
				loomid: loom_id,
				rawids: rawids,
			};
		},

		openBomPot() {
			this.dialog.pot = true;
		},
		openBomColor() {
			this.dialog.color = true;
		},
		getQuantity() {
			return [
				{
					dosage: { type: "ge", value: this.form.quantity ?? 0 },
					status_id: 0,
				},
			];
		},
		open(mode = "add") {
			this.mode = mode;
			this.visible = true;
			return this;
		},
		//选择小样
		selectColor(data, items) {
			this.dialog.color = false;
			this.form.color_id = data.main.id;
			this.form.color = data.main;
			this.form.raw = items.map((item) => {
				if (item.material) {
					this.calcAuxiliaryQuantity(item);
					this.calcAuxiliaryAmount(item);
					return item;
				} else {
					this.$message.error("配方的某项未找到匹配物料！");
					return false;
				}
			});
			this.form.rscode = data.rscode;
			this.form.dyecraft = data.dyecraft ?? {};
			this.form.dyeendcraft = {};
			this.form.revision_id = data.id;
			this.resetComputAuxiliary();
		},
		//选择小样
		selectPotColor(data, items) {
			this.dialog.pot = false;
			this.form.color_id = data.color.id;
			this.form.color = data.color;
			this.form.raw = items.map((item) => {
				this.calcAuxiliaryQuantity(item);
				this.calcAuxiliaryAmount(item);
				return item;
			});
			this.form.rscode = data.rscode;
			this.form.rscodeend = data.rscodeend;
			this.form.dyecraft = data.dyecraft ?? {};
			this.form.dyeendcraft = data.dyeendcraft ?? {};

			this.form.revision_id = data.revision_id;
		},
		//重新计算助剂用量，金额
		resetComputAuxiliary() {
			this.form.raw = this.form.raw.map((item) => {
				return this.calcAuxiliaryAmount(
					this.calcAuxiliaryQuantity(item)
				);
			});
		},
		//计算金额
		calcAuxiliaryAmount(item) {
			if (item === false) {
				return item;
			}
			item.cost = parseFloat(
				XEUtils.toFixed(
					(item.material.average_price * item.quantity) /
						(1999 - item.uunit_id * 999),
					2
				)
			);
			return item;
		},
		//计算比例
		calcAuxiliaryRate(item) {
			if (item === false) {
				return item;
			}
			// uunit_ 1g 2kg
			let quantity = item.quantity;
			if (item.uunit_id == 1) {
				quantity = item.quantity / 1000;
			}

			if (item.ounit_id == 1) {
				//%*数量/100   =>KG
				item.rate = (quantity * 100) / this.form.yarn_quantity;
			} else {
				//g/L*数量/1000  =>KG
				item.rate = (quantity * 1000) / this.form.bath_qty;
			}
			return item;
		},
		//计算数量
		calcAuxiliaryQuantity(item) {
			if (item === false) {
				return item;
			}
			delete item.id;
			delete item.quantity;
			delete item.new_rate;
			if (item.ounit_id == 1) {
				//%*数量/100   =>KG
				item.quantity = (this.form.yarn_quantity * item.rate) / 100;
			} else {
				//g/L*数量/1000  =>KG
				item.quantity = (this.form.bath_qty * item.rate) / 1000;
			}

			// uunit_ 1g 2kg
			//根据用量设置单位
			if (item.quantity < 1) {
				item.uunit_id = 1;
				item.uunit.name = "g";
				item.quantity = item.quantity * 1000;
			} else {
				item.uunit_id = 2;
				item.uunit.name = "kg";
			}
			item.quantity = parseFloat(XEUtils.toFixed(item.quantity, 6));

			return item;
		},
		//表单提交方法
		submit() {
			this.$refs.dialogPotdata.validate(async (valid) => {
				if (valid) {
					if (this.repairpot.includes("重新开卡")) {
						this.$refs.dialogForm.validate(async (valid) => {
							if (valid) await this.postdata();
						});
					} else await this.postdata();
				}
			});
		},
		async postdata() {
			this.isSaveing = true;
			var res = await this.$API.pro.pot.repair.post({
				form: this.form,
				potdata: this.potdata,
				repairpot: this.repairpot,
			});
			this.isSaveing = false;
			if (res.code == 200) {
				this.$emit("success", this.form, this.mode);
				this.visible = false;
				this.$message.success("开卡成功");
			}
		},
		// async getItems(id) {
		//   console.log(id);
		// },
		loomSelect(data) {
			this.form.loom_id = data.id;
			this.form.ratio = data.ratio;
			this.form.dosage = data.dosage;
			this.resetComputAuxiliary();
		},
		async getItems(id) {
			let res = await this.$API.pro.wip.list.get({
				filter: [{ pro_pot_id: id }],
			});
			this.potdata.details = res.data.rows;
		},
		async getPotInfo(id) {
			let res = await this.$API.pro.pot.info.get({
				filter: [{ id: id }],
			});
			Object.assign(this.form, tool.removeNull(res.data));
		},
		//表单注入数据
		setData(data, details) {
			console.log(data);
			Object.assign(this.potdata, tool.removeNull(data));
			this.form.yarn_quantity = data.yarn_quantity;
			this.form.loom = data.loom;
			this.form.dosage = data.dosage;
			this.form.ratio = data.ratio;
			this.form.lot_name = data.lot_name;
			this.form.material_id = data.material_id;
			this.form.loom_id = data.loom_id;
			// this.getPotInfo(data.id);
			this.getItems(data.id);
			this.form.wip_ids = details.map((v) => v.id);
			this.form.feeding_ratio = 940;
			this.form.quantity = (data.yarn_quantity / 940) * 1000;
			return this;
			// this.getItems(data.id);
		},
	},
};
</script>

<style>
.attachments .el-upload--picture-card,
.attachments .el-upload-list--picture-card .el-upload-list__item {
	width: 100px;
	height: 100px;
	overflow: hidden;
}
</style>
